import { OzTokenABI } from '@app/contract/oztoken'
import { InputData } from 'ethereum-input-data-decoder'
import InputDataDecoder from 'ethereum-input-data-decoder'

const ADDRESS_PREFIX = '41'

class TokenDecoder {
    private tronWeb: any
    private decoder: InputDataDecoder

    constructor(tronWeb: any) {
        this.tronWeb = tronWeb
        this.decoder = new InputDataDecoder(JSON.parse(OzTokenABI))
    }

    hexToAddress(hex: string) {
        hex = ADDRESS_PREFIX + hex
        return this.tronWeb.address.fromHex(hex)
    }

    decodeTransfer(from: string, input: string) {
        let inputData: InputData | undefined
        try {
            inputData = this.decoder.decodeData(input)
        } catch (error) {
            return
        }

        switch (inputData.method) {
            case 'transfer': {
                const to = this.hexToAddress(inputData.inputs[0].toString())
                const amount = inputData.inputs[1].toString()
                return { from, to, amount }
            }
            case 'transferFrom': {
                const from = this.hexToAddress(inputData.inputs[0].toString())
                const to = this.hexToAddress(inputData.inputs[1].toString())
                const amount = inputData.inputs[2].toString()
                return { from, to, amount }
            }
            default:
                return
        }
    }
}

export { TokenDecoder }
